package handler

import (
	"car-trade-hub/cache"
	"car-trade-hub/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Car(c *gin.Context) {
	name := c.PostForm("name")
	types := c.PostForm("type")
	price := c.PostForm("price")
	num := c.PostForm("num")
	time := c.PostForm("time")
	data := model.Car{
		Name:  name,
		Types: types,
		Price: price,
		Num:   num,
		Time:  time,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
}
func Order(c *gin.Context) {
	orderid, _ := strconv.Atoi(c.PostForm("orderid"))
	ordertime := c.PostForm("ordertime")
	ordercomment := c.PostForm("ordercomment")
	data := model.Order{
		OrderId:      orderid,
		OrderTime:    ordertime,
		OrderComment: ordercomment,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
}

func List(c *gin.Context) {
	/*
		SELECT
		orders.order_id as OrderId,
		orders.order_time as OrderTime,
		orders.order_comment as OrderComment,
		cars.name as Name,
		cars.types as Types,
		cars.price as Price,
		cars.num as Num,
		cars.time as Time,
		FROM
		cars
		LEFT JOIN orders on orders.cid=cars.id
	*/
	var list []model.CarOrder
	redis_key := "car_order_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("cars").Select(
			"orders.order_id as OrderId",
			"orders.order_time as OrderTime",
			"orders.order_comment as OrderComment",
			"cars.name as Name",
			"cars.types as Types",
			"cars.price as Price",
			"cars.num as Num",
			"cars.time as Time",
		).Joins("LEFT JOIN orders on orders.cid=cars.id").Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": list,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var list model.CarOrder
	redis_key := "car_order_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("cars").Select(
			"orders.order_id as OrderId",
			"orders.order_time as OrderTime",
			"orders.order_comment as OrderComment",
			"cars.name as Name",
			"cars.types as Types",
			"cars.price as Price",
			"cars.num as Num",
			"cars.time as Time",
		).Joins("LEFT JOIN orders on orders.cid=cars.id").Where("cars.id=?", id).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": list,
	})
}
